package net.towee.client.com.app.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;

import net.towee.client.com.app.UserFeedback;
import net.towee.server.rpc.services.ToweeServiceAsync;

public class UserFeedbackPresenter implements UserFeedback, ClickHandler {

	public interface Display extends IsWidget {
		void showForm();
		
		String getUserName();
		
		String getMessage();
		
		HasClickHandlers getSendButton();
		
		void noUserName();
		void noMessage();
		boolean hasErrors();

		void onSending();

		void onSend();
	}
	
	// Injected
	private final ToweeServiceAsync service;
	private final Display display;
	
	@Inject
	public UserFeedbackPresenter(Display display, ToweeServiceAsync service){
		this.service = service;
		this.display = display;
		
		display.getSendButton().addClickHandler(this);
	}
	
	@Override
	public void go(HasWidgets container) {
		display.showForm();
	}

	@Override
	public void onClick(ClickEvent event) {
		if(display.getUserName().isEmpty()) display.noUserName();
		if(display.getMessage().isEmpty()) display.noMessage();
		if(!display.hasErrors()) {
			display.onSending();
			service.sendFeedback( display.getUserName(), display.getMessage(), new AsyncCallback<Boolean>() {
				@Override
				public void onFailure(Throwable caught) {}

				@Override
				public void onSuccess(Boolean result) {
					display.onSend();		
				}
			});
		}
	}

}
